package test.leecode.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson.annotation.JSONField;


public class ListNode {

    @JSONField(ordinal = 1)
    public int val;
    @JSONField(ordinal = 2)
    public ListNode next;

    public ListNode(int value, ListNode next) {
      this.val = value;
      this.next = next;
    }

    public ListNode(int value) {
      this(value,null);
    }

    public static ListNode arrayListNode(int[] array) {
      ListNode result = null;
      ListNode temp = null;
      for (int i = 0; i < array.length; i++) {
          int v = array[i];
          if(result==null) {
            result = new ListNode(v);
          }else{
            if(Objects.isNull(result.next)) {
              result.next = new ListNode(v);
              temp = result.next;
            }else {
              temp.next = new ListNode(v);
              temp = temp.next;
            }
          }
      }
      return result;
    }

    public static int[] node2Array(ListNode l1) {
        List<Integer> list = new ArrayList<>();
        while (l1.next != null) {
            list.add(l1.val);
            l1 = l1.next;
        }
        list.add(l1.val);
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}
